﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.WebSockets;

namespace Bigger.Study.Web.Controllers
{
    public class WebSocketController : Controller
    {

        public ActionResult WebSocketDemo()
        {
            return View();
        }

        public void StartWebSocketServer()
        {
            this.HttpContext.AcceptWebSocketRequest(ProcessWebSocket);
        }

        private async Task ProcessWebSocket(AspNetWebSocketContext objAspNetWebSocketContext)
        {
            WebSocket objWebSocket = objAspNetWebSocketContext.WebSocket;
            while (true)
            {
                if (objWebSocket.State != WebSocketState.Open)
                {
                    break;
                }
                ArraySegment<byte> objArraySegment = new ArraySegment<byte>(new byte[2048]);
                WebSocketReceiveResult objWebSocketReceiveResult = await objWebSocket.ReceiveAsync(objArraySegment, CancellationToken.None);

                string receiveMessage = Encoding.UTF8.GetString(objArraySegment.Array, 0, objWebSocketReceiveResult.Count);
                string sendMessage = string.Format("{0}：{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), receiveMessage);

                objArraySegment = new ArraySegment<byte>(Encoding.UTF8.GetBytes(sendMessage));
                await objWebSocket.SendAsync(objArraySegment, WebSocketMessageType.Text, true, CancellationToken.None);
            }
        }

    }
}
